/*
 * @(#)PamLoginModule.java	1.01
 *
 */

package com.dongnam.security.auth.module.tomcat;

import java.util.*;
import java.io.IOException;

import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;

import org.jvnet.libpam.PAM;
import org.jvnet.libpam.PAMException;
import org.jvnet.libpam.UnixUser;

import com.dongnam.security.auth.principal.*;


/**
 * <p> This LoginModule authenticates users with a password.
 * 
 * <p> This LoginModule recognizes the debug option.
 * If set to true in the login Configuration,
 * debug messages will be output to the output stream, System.out.
 *
 * @version 1.01
 */
public class PamLoginModule implements LoginModule {

    // initial state
    private Subject subject;
    private CallbackHandler callbackHandler;
    private Map sharedState;
    private Map options;

    // configurable option
    private boolean debug = false;
    private String service = "sshd";	// PAM service to use

    // the authentication status
    private boolean succeeded = false;
    private boolean commitSucceeded = false;

    // username and userGroup(ie. role)
    private String username;
    private Set<String>	userGroup;
    
    /**
     * Initialize this <code>LoginModule</code>.
     *
     * <p>
     *
     * @param subject the <code>Subject</code> to be authenticated. <p>
     *
     * @param callbackHandler a <code>CallbackHandler</code> for communicating
     *			with the end user (prompting for user names and
     *			passwords, for example). <p>
     *
     * @param sharedState shared <code>LoginModule</code> state. <p>
     *
     * @param options options specified in the login
     *			<code>Configuration</code> for this particular
     *			<code>LoginModule</code>.
     */
    public void initialize(Subject subject, 
	           CallbackHandler callbackHandler,
			 Map<java.lang.String, ?> sharedState, 
			 Map<java.lang.String, ?> options) {
 
		this.subject = subject;
		this.callbackHandler = callbackHandler;
		this.sharedState = sharedState;
		this.options = options;
	
		// initialize any configured options.  You can add any options here, such as the DB connection to audit trail
		debug = "true".equalsIgnoreCase((String)options.get("debug"));
		if (options.containsKey("service")) {
			service = (String)options.get("service");
		}
    }

    /**
     * Authenticate the user by prompting for a user name and password.
     *
     * <p>
     *
     * @return true in all cases since this <code>LoginModule</code>
     *		should not be ignored.
     *
     * @exception FailedLoginException if the authentication fails. <p>
     *
     * @exception LoginException if this <code>LoginModule</code>
     *		is unable to perform the authentication.
     */
    public boolean login() throws LoginException {
	
		// prompt for a user name and password
		if (callbackHandler == null) {
		    throw new LoginException("Error: no CallbackHandler available " +
				"to garner authentication information from the user");
		}
		
		Callback[] callbacks = new Callback[2];
		callbacks[0] = new NameCallback("user name: ");
		callbacks[1] = new PasswordCallback("password: ", false);
	 
	    char[] password;
		try {
		    callbackHandler.handle(callbacks);
		    username = ((NameCallback)callbacks[0]).getName();
		    char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
		    if (tmpPassword == null) {
		    	// treat a NULL password as an empty password
		    	tmpPassword = new char[0];
		    }
		    password = new char[tmpPassword.length];
		    System.arraycopy(tmpPassword, 0,
				password, 0, tmpPassword.length);
		    ((PasswordCallback)callbacks[1]).clearPassword();
	 
		} catch (java.io.IOException ioe) {
		    throw new LoginException(ioe.toString());
		} catch (UnsupportedCallbackException uce) {
		    throw new LoginException("Error: " + uce.getCallback().toString() +
			" not available to garner authentication information " +
			"from the user");
		}
	
		// verify the username/password
		try {
			UnixUser uuser = new PAM(service).authenticate(username, new String(password));
	
			this.userGroup = uuser.getGroups();
		    succeeded = true;

		    // authentication succeeded!!!
		    if (debug) {
				System.out.println("\t\t[PamLoginModule] " +
						"authentication succeeded");
		    }
		    // TODO: You can add audit trail here
		    
			return true;
		} catch (PAMException e){
			System.out.println(e);

		    succeeded = false;
		    username = null;
		    password = null;

		    // TODO: You can add audit trail here
		    
			throw new FailedLoginException("Unable to login");
		}
    }

    /**
     * <p> This method is called if the LoginContext's
     * overall authentication succeeded
     * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
     * succeeded).
     *
     * <p> If this LoginModule's own authentication attempt
     * succeeded (checked by retrieving the private state saved by the
     * <code>login</code> method), then this method associates a
     * <code>UserPrincipal</code>
     * with the <code>Subject</code> located in the
     * <code>LoginModule</code>.  If this LoginModule's own
     * authentication attempted failed, then this method removes
     * any state that was originally saved.
     *
     * <p>
     *
     * @exception LoginException if the commit fails.
     *
     * @return true if this LoginModule's own login and commit
     *		attempts succeeded, or false otherwise.
     */
    public boolean commit() throws LoginException {
		if (succeeded == false) {
		    return false;
		} else {
		    // add a Principal (authenticated identity)
		    // to the Subject
	
			subject.getPrincipals().clear();
			
			// Catalina expects the first Principal is the user, and then followed by roles
			subject.getPrincipals().add(new UserPrincipal(username));	// Add user first
			
		    // then add roles
		    RolePrincipal rolePrincipal;
			for (String ug : this.userGroup) {
			    rolePrincipal = new RolePrincipal(ug);
			    if (!subject.getPrincipals().contains(rolePrincipal)){
			    	subject.getPrincipals().add(rolePrincipal);
			    }
			}
	
		    if (debug) {
		    	System.out.println("\t\t[" + this + "] " +
					"added " + userGroup + " to Subject");
		    }
	
		    // in any case, clean out state
		    username = null;
	
		    commitSucceeded = true;
		    return true;
		}
    }

    /**
     * <p> This method is called if the LoginContext's
     * overall authentication failed.
     * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
     * did not succeed).
     *
     * <p> If this LoginModule's own authentication attempt
     * succeeded (checked by retrieving the private state saved by the
     * <code>login</code> and <code>commit</code> methods),
     * then this method cleans up any state that was originally saved.
     *
     * <p>
     *
     * @exception LoginException if the abort fails.
     *
     * @return false if this LoginModule's own login and/or commit attempts
     *		failed, and true otherwise.
     */
    public boolean abort() throws LoginException {
    	if (succeeded == false) {
    		return false;
		} else if (succeeded == true && commitSucceeded == false) {
		    // login succeeded but overall authentication failed
		    succeeded = false;
		    username = null;
		    if (userGroup != null) {
		    	userGroup = null;
		    }
		} else {
		    // overall authentication succeeded and commit succeeded,
		    // but someone else's commit failed
		    logout();
		}
		return true;
    }

    /**
     * Logout the user.
     *
     * <p> This method removes the <code>UserPrincipal</code> & <code>RolePrincipal</code> 
     * that was added by the <code>commit</code> method.
     *
     * <p>
     *
     * @exception LoginException if the logout fails.
     *
     * @return true in all cases since this <code>LoginModule</code>
     *          should not be ignored.
     */
    public boolean logout() throws LoginException {
		if (debug) {
			System.out.println("\t\t[" + this + "] logout");
		}
	    // TODO: You can add audit trail here
		
		subject.getPrincipals().clear();
		succeeded = false;
		commitSucceeded = false;
		username = null;
		if (userGroup != null) {
			userGroup = null;
    	}
		return true;
    }
}
